package com.woniu.market_stall_web.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.woniu.market_stall_web.entity.User;
import com.woniu.market_stall_web.service.MailService;
import com.woniu.market_stall_web.service.UserService;
import com.woniu.market_stall_web.vo.UserVo;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService ;

    @Autowired
    private MailService mailService;

    @RequestMapping("/login")
    public String login(String username, String password, String code, Map map, HttpSession session){
        String sessionCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (!sessionCode.equals(code)){
            map.put("errorInfo","验证码错误!");
            return "login" ;
        }else  {
            User user = userService.login(username);
            if(user == null){
                map.put("errorInfo","账号不存在!");
                return "login" ;
            }else if (user.getPassword().equals(password)){
                //登录正确
                session.setAttribute("userInfo",user);

                return "redirect:/index/main" ;
            }else {
                map.put("errorInfo","密码错误!");
                return "login" ;
            }
        }
    }

    @Autowired
    private Producer producer;

    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        // 生成文字验证码
        String text = producer.createText();
        // 生成图片验证码
        BufferedImage image = producer.createImage(text);
        // 保存到验证码到 session  或者 验证存储到redis
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    @RequestMapping("/register")
    public String register(String username,String password,String cellphone,String email){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setCellphone(cellphone);
        user.setEmail(email);
        user.setInsertTime(new Date());
        userService.addUser(user);

        return "redirect:/handle/info";

    }


    @RequestMapping("/checkName")
    @ResponseBody
    public int checkName(@RequestParam("username") String username){

        int i = userService.checkName(username);
        return i;
    }
    @PostMapping("/verify")
    @ResponseBody
    public String verify(User user) {

        return mailService.selectUserByUsernameAndEmail(user);
    }


    /**
     * 发送找回密码验证码
     * @param email
     * @param httpSession
     * @return
     */
    @PostMapping("/sendEmail2/{email}")
    @ResponseBody
    public String sendEmail2(@PathVariable String email, HttpSession httpSession) {
        boolean flag = mailService.sendMimeMail2(email, httpSession);
        return flag ? "success" : "false";
    }

    /**
     * 注册
     * @param userVo
     * @param session
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    public String update(UserVo userVo, HttpSession session) {
        boolean flag = mailService.updateUser(userVo, session);
        session.removeAttribute("code");
        return flag ? "success" : "false";
    }

    @RequestMapping("/exit")
    public String exit(HttpSession session){
        session.removeAttribute("userInfo");
        return "login" ;
    }



    @RequestMapping("/all")
    public String all(Map map,HttpSession session){
        User userInfo = (User) session.getAttribute("userInfo");
        User list = userService.selectUser(userInfo.getId());
        map.put("userList",list);
        return "news";
    }


    @GetMapping("/edit/{id}")
    public String toEdit(@PathVariable Integer id, Model model){
        model.addAttribute("user",userService.selectUser(id));
        return "edit";
    }


    @PostMapping("/editUser")
    public String editUser(User user, RedirectAttributes redirectAttributes){
        boolean b = userService.update(user);
        if (b){
            redirectAttributes.addFlashAttribute("message","更新成功");
            return "redirect:/user/all";
        }else {
            redirectAttributes.addFlashAttribute("message","更新失败");
            return "news";
        }

    }
}
